<?php
/**
 * Router class
 *
 *
 * @package    lib
 * @subpackage lib_view
 * @author     Juan Carlos Jarquin (zetta)
 * @author     $LastChangedBy$
 * @version    1.1, SVN: $Id$
 */
class View
{
  
  /**
   * @var Twig_Environment
   */
  private $twig;
  
  private $template;
  
  private $controller = '';
  private $fileName = '';
  

  
  /**
   * @var string
   */
  private $viewPath = 'views';
  
  /**
   * @var string
   */
  private $cachePath = 'cache';
  
  /**
   * @var array
   */
  private $params = array();
  
  private static $instance = null;
  
  private function View($viewPath,$cachePath)
  {
    $this->viewPath = $viewPath;
    $this->cachePath = $cachePath;
    if(!is_writable($this->cachePath))
      throw new ViewException("View Cache path ($this->cachePath) is not writable");
    $loader = new Twig_Loader_Filesystem($this->viewPath);
    $this->twig = new Twig_Environment($loader, array('cache' => $this->cachePath,'auto_reload' => true));
    #$this->twig = new Twig_Environment($loader, array('cache' => false));
  }
  
  public function getInstance($viewPath = null,$cachePath = null)
  {
    if(is_null(self::$instance))
      self::$instance = new View($viewPath,$cachePath);
    return self::$instance;
  }
  
  
  public function setFileName($fileName)
  {
     $this->fileName = $fileName;
  }
  
  public function __set($key,$value)
  {
    $this->params[$key] = $value;
  }
  
 
  public function prepare()
  {
    $this->controller = Request::getInstance()->getControllerName();
    return $this;
  }
  
  public function render()
  {
    $template = $this->twig->loadTemplate($this->controller.'/'.$this->fileName);
    echo $template->render($this->params);
  }
  
}
